// Surface
// (c) jimon game studio

#include "CSurface.h"

namespace je
{
	namespace scene
	{
		//! Constructor
		CSurface::CSurface(video::IRender * Render,video::RenderOperationType Type,video::jeRenderOperation * Operation)
			:CurrentRender(Render),CurrentSharedMaterial(NULL),CurrentUseUniqueMaterial(false),CurrentOperationType(Type),CurrentOperation(Operation)
		{
			CurrentOperation->Grab();
		}

		//! Destructor
		CSurface::~CSurface()
		{
			SetMaterialResource(NULL);
			CurrentOperation->Drop();
		}

		//! Set Material Resource
		void CSurface::SetMaterialResource(media::jeMaterialResource * MaterialResource,u1 UseUniqueMaterial,u1 UseUniqueTextures,u1 UseUniqueShader)
		{
			if(CurrentSharedMaterial)
			{
				if(CurrentUseUniqueMaterial)
					JE_MATERIALRESOURCE_DROP(CurrentSharedMaterial,this,CurrentRender)
				else
					JE_MATERIALRESOURCE_SHARED_DROP(CurrentSharedMaterial,CurrentRender)
				CurrentSharedMaterial = NULL;
			}

			CurrentUseUniqueMaterial = UseUniqueMaterial;

			if(MaterialResource)
			{
				if(CurrentUseUniqueMaterial)
					JE_MATERIALRESOURCE_GRAB(CurrentSharedMaterial,MaterialResource,this,UseUniqueTextures,UseUniqueShader,CurrentRender)
				else
					JE_MATERIALRESOURCE_SHARED_GRAB(CurrentSharedMaterial,MaterialResource,CurrentRender)
			}
		}

		//! Get Material Resource
		media::jeMaterialResource * CSurface::GetMaterialResource()
		{
			if(CurrentSharedMaterial)
				return JE_MATERIALRESOURCE(CurrentSharedMaterial->GetResourceName());
			else
				return NULL;
		}

		//! Get Shared Material Resource
		media::jeSharedMaterial * CSurface::GetSharedMaterialResource()
		{
			return CurrentSharedMaterial;
		}

		//! Get Render
		video::IRender * CSurface::GetRender()
		{
			return CurrentRender;
		}

		//! Get Render Operation
		video::jeRenderOperation * CSurface::GetRenderOperation()
		{
			return CurrentOperation;
		}

		//! Get Render Operation Type
		video::RenderOperationType CSurface::GetRenderOperationType()
		{
			return CurrentOperationType;
		}

		//! Get Material
		video::jeMaterial * CSurface::GetMaterial()
		{
			if(CurrentSharedMaterial)
				return CurrentSharedMaterial->GetMaterial();
			else
				return NULL;
		}

		//! On Render
		void CSurface::OnRender(const jeMatrix4f & AbsoluteModelMatrix)
		{
			CurrentRender->SetMatrix(AbsoluteModelMatrix,video::RMT_MODEL);
			CurrentRender->SetMaterial(GetMaterial());
			CurrentRender->RenderOperation(CurrentOperationType,CurrentOperation);
		}

		//! Create Surface
		ISurface * CreateSurface(video::IRender * Render,video::RenderOperationType Type,video::jeRenderOperation * Operation)
		{
			ISurface * Surface = NULL;
			JENEW(Surface,CSurface(Render,Type,Operation))
			return Surface;
		}
	}
}
